<?php
//111.230.193.165
//8080
header('Content-Type:text/html;charset=utf-8;');
date_default_timezone_set("PRC");
$params = array(
    'exchangeName' => 'delayed_exchange_test',
    'queueName' => 'delayed_queue_test',
    'routeKey' => 'delayed_route_test',
);
// Cye@88MnFF$xMM
// admin   ZBJ#38%ice@SD66
/*
	$db_user = "DbXmB88_dbMnCB";
	$db_password = 'MMccl@dmi$yX88';
	*/
$connectConfig = array(
    'host' => 'localhost',
    'port' => 5672,
    'login' => 'admin',
    'password' => 'admin2021',
    'vhost' => '/'
);

//var_dump(extension_loaded('amqp')); 判断是否加载amqp扩展
//exit();
try {
    $conn = new AMQPConnection($connectConfig);
    $conn->connect();
    if (!$conn->isConnected()) {
        //die('Conexiune esuata');
        //TODO 记录日志
        echo 'rabbit-mq 连接错误:', json_encode($connectConfig);
        exit();
    }
    $channel = new AMQPChannel($conn);
    if (!$channel->isConnected()) {
        // die('Connection through channel failed');
        //TODO 记录日志
        echo 'rabbit-mq Connection through channel failed:', json_encode($connectConfig);
        exit();
    }
    $exchange = new AMQPExchange($channel);
    $exchange->setName($params['exchangeName']);
    $exchange->setType('x-delayed-message'); //x-delayed-message类型
    /*RabbitMQ常用的Exchange Type有三种：fanout、direct、topic。

      fanout:把所有发送到该Exchange的消息投递到所有与它绑定的队列中。

      direct:把消息投递到那些binding key与routing key完全匹配的队列中。

      topic:将消息路由到binding key与routing key模式匹配的队列中。*/
    $exchange->setArgument('x-delayed-type','direct');
    $exchange->declareExchange();

    //$channel->startTransaction();
    //RabbitMQ不容许声明2个相同名称、配置不同的Queue,否则报错
    $queue = new AMQPQueue($channel);
    $queue->setName($params['queueName']);
    $queue->setFlags(AMQP_DURABLE);
    $queue->declareQueue();

    //绑定队列和交换机
    $queue->bind($params['exchangeName'], $params['routeKey']);
    //$channel->commitTransaction();
} catch(Exception $e) {

}
$ttl = 1000 * 300;
for($i=1;$i<6;$i++){
    //生成消息
    echo '发送时间：'.date("Y-m-d H:i:s", time()).PHP_EOL;
    echo 'i='.$i.'，延迟'.$i.'秒'.PHP_EOL;
    $message = json_encode(['order_id'=>'id-'.time().$i,'i'=>$i]);
    $exchange->publish($message, $params['routeKey'], AMQP_NOPARAM, ['headers'=>['x-delay'=> $ttl*$i]]);
    //sleep(2);
}
$conn->disconnect();